import Decimal from 'decimal.js';

// 解析地址
export const validUrl = url => {
  try {
    if (!url) {
      return false;
    }
    if (url.includes('sdzhuisu.com') && url.includes('?')) {
      let opts = {};
      const params = url.split('?')[1].split('&');
      params.forEach(item => {
        const opt = item.split('=');
        opts[opt[0]] = opt[1];
      });
      return opts;
    } else {
      return {};
    }
  } catch (e) {
    console.log('解析地址 ', e);
  }
};

// 校验文件地址是否可用
export const verifyUrl = url => {
  return new Promise((resolve, reject) => {
    fetch(url, { method: 'HEAD' })
      .then(response => {
        // 检查响应状态码
        if (response.ok) {
          resolve();
        } else {
          reject();
        }
      })
      .catch(() => {
        reject();
      });
  });
};

/**
 * svg图标
 * @param {String} svg svg图标
 * @return {String}
 * */
export const svgIcon = svg => `data:image/svg+xml,${encodeURIComponent(svg)}`;

/**
 * 线上图标
 * @param {String} name 图标名称
 * @return {String}
 * */
export const publicIcon = name => {
  let path = 'https://vshitang.sdzhuisu.com/wst/profile/xcx/';
  return `${path}${name}`;
};

/**
 * 价格单位转换，100分 = 1元
 * @param {Number|String} price 价格
 * @return {Number}
 * */
export const priceUnit = price => {
  const priceDec = new Decimal(price);
  const step = new Decimal(100);
  return priceDec.div(step).toNumber();
};
